﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using Sok.Munkae.ApplicationServices;
using Sok.Munkae.ApplicationServices.Membership;
using Sok.Munkae.Core;

namespace Sok.Munkae.ApplicationServices
{
    public interface IAuthenticationService
    {
        bool Authenticate(string userName, string password, bool rememberMe);
        void SignOut();
        User GetAuthenticatedUser(IPrincipal principal);
    }

    public class AuthenticationService : IAuthenticationService
    {
        private IMembershipService membershipService;
        private IAuthenticationProvider authenticationProvider;
        private IUserContext userContext;

        public AuthenticationService(IMembershipService membershipService,IAuthenticationProvider authenticationProvider,IUserContext userContext)
        {
            this.membershipService = membershipService;
            this.authenticationProvider = authenticationProvider;
            this.userContext = userContext;
        }
        public bool Authenticate(string userName, string password, bool rememberMe)
        {
            UserValidationResult result = membershipService.ValidateUser(userName, password);
            if(result.ResultDisposition != UserValidationResultDisposition.Success)
            {
                return false;
            }
            authenticationProvider.SetAuthCookie(result.User.Identity.Name, (rememberMe != null));
            userContext.SetUser(result.User.Init());
            
            return true;
        }

        public void SignOut()
        {
            authenticationProvider.SignOut();
            authenticationProvider.RedirectToLogin();
        }

        public User GetAuthenticatedUser(IPrincipal principal)
        {
            if(principal != null && principal.Identity != null && principal.Identity.IsAuthenticated)
            {
                return membershipService.RetrieveUser(principal.Identity.Name).Init();
            }
        
            return null;
        }
    }

}
